<template>
  <SwModal :isShow.sync="isShowTradeBox" :isShowBg="true" :onClosed = "onClosed" :okText="''" :isCloseOnClickBg="true">
    <div class="buyAndSell">
      <a class="close" @click="closeBuyOrSell"><img src="./../images/close2.png"></a>
      <div class="title">
        {{lang['determine the order']}}
      </div>

      <h3 class="buyTitle" :class="{red : isBuyOrSell}"  >
        <font v-show="!isBuyOrSell">{{lang['buy for a rise']}}</font><font v-show="isBuyOrSell">{{lang['offtake']}}</font> {{pair.coinCode}}
        <a>
          <em>{{lang['because of the sharp fluctuation of the market']}}</em>
        </a>
        <span >
          {{lang['olease confirm within 30 seconds']}}
        </span>
      </h3>

      <ul class="list">
        <li>
          <label><span>{{lang['price']}}</span></label>
          <div class="form-group">
            <em>
              {{currentOrder.FluctuationRate > 0 ? orderCurrentPrice(currentOrder.FluctuationRate, currentOrder.newPrice) : currentOrder.newPrice | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
              <!-- {{currentOrder.FluctuationRate > 0 ?  parseFloat((currentOrder.newPrice * currentOrder.FluctuationRate) || 0) : currentOrder.newPrice | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}} -->
              <font class="cny">{{pair.currencyCode}}</font>
            </em>
          </div>
        </li>

        <li>
          <label>{{lang['quantity']}}</label>
          <div class="form-group">
            <input type="text" name="" value="" maxlength="9" ref="quantity" v-model="quantity" :placeholder="!isBuyOrSell ? lang['maximum available'] + currentOrder.UseQuantity : lang['maximum saleable'] + currentOrder.UseQuantity" @keyup = "calculateScaleQuantity">
            <font class="cny">{{pair.coinCode}}</font>
          </div>
        </li>

        <li>
          <label>{{lang['amount of money']}}</label>
          <div class="form-group">
            <input type="text" name="" value="" maxlength="15" v-model="amount" ref="amount" @keyup="calculateScaleMount">
            <!--   -->
            <font class="cny">{{pair.currencyCode}}</font>
          </div>
        </li>

         <li v-show="!isBuyOrSell">
          <label></label>
          <div class="warning">
           {{lang['c2c user name platform transaction']}}
          </div>
        </li>


      </ul>
      <button type="button" class="subtimBox" @click="closeBuyOrSell">({{time}}s) {{lang['automatic cancellation']}}</button>
      <button type="button" class="subtimBox blue" v-bind:class="{ active: !isClickBuysell }" v-show="!isBuyOrSell" @click = 'buyBth'>{{lang['Confirm Buy']}}</button>
      <button type="button" class="subtimBox blue" v-bind:class="{ active: !isClickBuysell }" v-show="isBuyOrSell" @click = 'sellBth'>{{lang['Confirm Sell']}}</button>
    </div>
  </SwModal>
</template>

<script>
import router from '@/router/index.js'
import SwModal from '@/components/SwModal'
import ModalApi from '@/components/SwModal/api.js'
import CheckCurrencyOnInput from '@/utils/CheckCurrencyOnInput.js'
import commonFilter from '@/filters/common.js'
import EventBus from '@/service/EventBus.js'
import Decimal from '@/libs/decimal.min.js'

export default {
  props: [
    'lang',
    'propIsShowTradeBox', // 弹窗控制
    'isBuyOrSell', // 买卖元素显示
    'customerVerification',  // 获取用户凭证信息
    'currentCoinAsset', // 获取币的可用数量
    'currentOrder', // 获取当前买卖列表 数据
    'currentFeeConfig', // 获取保证金
    'pair',
    'pairInfo', // 最新价 24小时最高最低价
    'getCustomerInfoList'
  ],
  data () {
    return {
      time: 30,
      isShowTradeBox: false,
      quantity: '',
      amount: '',
      isClickBuysell: true,
      interval: null
    }
  },
  watch: {
    isShowTradeBox (nv) {
      this.$emit('update:propIsShowTradeBox', nv)
    },
    propIsShowTradeBox (nv) {
      this.isShowTradeBox = nv
      if (this.isShowTradeBox) {
        this.init()
      }
    }
  },
  components: {
    SwModal
  },
  methods: {
    orderCurrentPrice (FluctuationRate, Price) {
      FluctuationRate = new Decimal(FluctuationRate || 0)
      return FluctuationRate.mul(Price || 0).toFixed(10)
    },
    assetDeficiency () {
      // let depositAmount = commonFilter.currency(commonFilter.ceilDecimal(this.getCustomerInfoList.Deposit, this.getCustomerInfoList.DepositPrecision) || 0, 'USD', '', this.getCustomerInfoList.DepositPrecision)

      // depositAmount = commonFilter.fillDecimal(depositAmount, this.getCustomerInfoList.DepositPrecision)

      let handle = ModalApi.confirm({
        modalClass: 'commonModal',
        isShowCloseBtn: true,
        isCloseOnClickBg: true,
        title: 'prompt message',
        content: () => {
          return this.lang['the account balance is lower than']
            .replace('{DepositAmount}', this.currentFeeConfig.DepositAmount || 0)
        },
        noText: '',  // '取消',
        okText: 'recharge', // '充值',
        isShowBg: true,
        ok: () => {
          router.push({path: '/assets'})
          handle.close()
        }
      })
    },
    // 买入
    buyBth () {
      if (!this.quantity) {
        let warning = this.lang['please enter the buy quantity'] // '请输入买入数量'
        ModalApi.message(warning)
        return
      }

      if (this.quantity > this.currentOrder.UseQuantity) {
        let warning = this.lang['the quantity of purchase exceeds the quantity of entrustment'] // 购买数量超过委托数量'
        ModalApi.message(warning)
        return
      }

      // 判断是否小于最小买入数量
      if (this.quantity < this.currentFeeConfig.BuyMinQuantity) {
        let warning = this.lang['Buying quantity is less than'] + this.currentFeeConfig.BuyMinQuantity + ' ' + this.pair.coinCode
        ModalApi.message(warning)
        return
      }
      if (!this.isClickBuysell) {
        return
      }
      this.isClickBuysell = false
     // 提交数据
      this.$host2.post('BuyIn/OrderBuyIn', {
        OrderId: this.currentOrder.ID, // 订单id
        Quantity: this.quantity // 数量
      }, {
        ignorableCodes: '51041,51050,51055,51021'
      })
      .then((res) => {
        if (res.StatusCode === '200') {
          ModalApi.message(this.lang['success'])
          this.closeBuyOrSell()
          setTimeout(() => {
            this.$emit('refreshCurrentAdList')
            EventBus.$emit('refreshUnfilledOrderList')
          }, 1000)
        } else if (res.StatusCode === '51050' || res.StatusCode === '51041' || res.StatusCode === '51055' || res.StatusCode === '51021') {
          this.closeBuyOrSell()
          this.assetDeficiency() // 资产或保证金不足提示
        }
        this.isClickBuysell = true
      })
    },

    // 卖出
    sellBth () {
      if (!this.quantity) {
        let warning = this.lang['please enter the quantity sold'] // '请输入卖出数量'
        ModalApi.message(warning)
        return
      }
      if (this.quantity > this.currentOrder.UseQuantity) {
        let warning = this.lang['sold in excess of commission'] // '卖出数量超过委托数量'
        ModalApi.message(warning)
        return
      }
      if (this.quantity < this.currentFeeConfig.SellMinQuantity) {
        let warning = this.lang['Sell quantity is less than'] + this.currentFeeConfig.SellMinQuantity + ' ' + this.pair.coinCode
        ModalApi.message(warning)
        return
      }

      if (!this.isClickBuysell) {
        return
      }
      this.isClickBuysell = false
     // 提交数据
      this.$host2.post('SellOut/OrderConfirm', {
        orderId: this.currentOrder.ID, // 订单id
        sellNum: this.quantity // 数量
      })
      .then((res) => {
        if (res.StatusCode === '200') {
          ModalApi.message(this.lang['success'])
          this.closeBuyOrSell()
          setTimeout(() => {
            this.$emit('refreshCurrentAdList')
            EventBus.$emit('refreshUnfilledOrderList')
          }, 1000)
        }
        this.isClickBuysell = true
      })
    },
    calculateScaleQuantity () {
       // 输入计算金额
      let currentOrder = this.currentOrder

      let floatPrice = Decimal.mul(currentOrder.newPrice, currentOrder.FluctuationRate).toFixed(10)
      let price = commonFilter.fillDecimal((currentOrder.FluctuationRate > 0 ? floatPrice : currentOrder.newPrice) || 0, this.pair.cyPrec)

      this.amount = commonFilter.fillDecimal(Decimal.mul(price, parseFloat(this.quantity) || 0).toFixed(10), 2)
    },
    calculateScaleMount () {
      // 输入计算数量
      let currentOrder = this.currentOrder

      let floatPrice = Decimal.mul(currentOrder.newPrice, currentOrder.FluctuationRate).toFixed(10)
      let price = commonFilter.fillDecimal((currentOrder.FluctuationRate > 0 ? floatPrice : currentOrder.newPrice) || 0, this.pair.cyPrec)

      this.quantity = commonFilter.fillDecimal(Decimal.div(parseFloat(this.amount) || 0, price).toFixed(10), this.pair.coinPrec || 0)
    },
    // 买币买币弹窗关闭
    closeBuyOrSell () {
      window.clearInterval(this.interval)

      this.isShowTradeBox = false // 关闭对话框
    },
    onClosed () {
      this.quantity = '' // 清空数量
      this.amount = ''
      this.time = 30
      window.clearInterval(this.interval)
    },
    init () {
      // 倒计时
      let me = this
      this.interval = window.setInterval(() => {
        if ((me.time--) <= 0) {
          me.time = 30
          me.isShowTradeBox = false
          window.clearInterval(me.interval)
        }
      }, 1000)
      // 倒计时
    }
  },
  mounted () {
    CheckCurrencyOnInput(this, this.$refs.quantity, 'quantity', () => (this.pair.coinPrec || 0))
    CheckCurrencyOnInput(this, this.$refs.amount, 'amount', 2)
  }
}
</script>
<style lang="less">
@import './../css/common.less';

// 买入
  .buyAndSell {
    position: relative;
    padding:0 40px;
    width: 400px;
    border-radius: 8px;

    .close {
      position: absolute;
      right: 40px;
      top: 15px;
      img {
        width:10px;
      }
    }

    .title {
      height: 46px;
      line-height: 46px;
      font-size: 16px;
      font-weight: 300;
      border-bottom: solid 1px #444c56;
      color: #fff;
    }

    .buyTitle {
      padding:12px 0;
      height: 24px;
      font-size: 14px;
      color:@green;

      &.red{
        color: @red;
      }
      span{
        float: right;
        font-size: 12px;
        color: #3782FF;
      }

      a {
        position: relative;
        float: right;
        margin-left: 5px;
        display: inline-block;
        width: 15px;
        height: 24px;
        background:url('./../images/pointPOut.png') no-repeat center;
        background-size: 14px 14px;
        em {
          position: absolute;
          right:-30px;
          top: 30px;
          z-index: 10;
          display: none;
          padding: 10px;
          width: 156px;
          line-height: 20px;
          background: #2D77BF;
          color: #fff;
          font-size: 12px;
          border-radius: 5px;

          &:after {
            position: absolute;
            right: 30px;
            top: -5px;
            content: "";
            display: block;
            width: 0;
            height: 0;
            border-bottom: solid 5px #2D77BF;
            border-left: solid 5px transparent;
            border-right: solid 5px transparent;
          }
        }

        &:hover em {
          display: inline-block;
        }
      }
    }

    .client {
      padding: 10px;
      line-height: 30px;
      color: #D4D4D4;
      background: #394555;
      border-radius: 5px;
    }

    .list {
      margin: 0 0 0;
      overflow: hidden;

      li {
        overflow: hidden;

        label {
          display: block;
          padding:15px 0 5px 10px;
          color: #fff;
        }

        .warning {
          color:#FD3117;
          line-height: 16px;
          font-size:12px;
        }
        .form-group {
          position: relative;
          width: 100%;
          color: #fff;

          em{
            display: block;
            width: 100%;
            line-height: 40px;
            text-indent: 10px;
            background: #212A35;
            border-radius: 5px;
          }
          input {
            padding: 0 10px;
            height: 40px;
            line-height: 40px;
            width:100%;
            background: #384C63;
            border-radius: 5px;
            color: #fff;
            box-sizing: border-box;

          }

          .cny {
            position: absolute;
            right: 10px;
            top: 10px;
            display: block;
            width: 60px;
            line-height: 20px;
            border-left: solid 1px rgba(255, 255, 255, 0.2);
            text-align: center;
            color: #fff;
          }
        }
      }
    }

    .subtimBox {
      display: inline-block;
      margin: 40px auto 40px 10%;
      width:35%;
      height: 36px;
      line-height: 36px;
      color: #fff;
      text-align: center;
      border-radius: 5px;
      background: #2A3441;

      &.blue {
        background: @blue;
      }

      &.active {
        background-color: #2A3441;
        cursor: not-allowed;
      }
    }
  }
</style>
